'use strict'

import constants from './constants'
import dispatcher from './dispatcher'
import Store from '../../base/Store'

const _state = {
    toast: {
        on: false
    },
    alert: {
        on: false
    },
    confirm: {
        on: false
    }
}

const _initialState = {
    toast: {
        on: false
    },
    alert: {
        on: false
    },
    confirm: {
        on: false
    }
}

class DialogStore extends Store {
    constructor() {
        super()
        dispatcher.register(action => {
            this.resetState()
            switch (action.actionType) {
                case constants.NOTIFY:
                    _state.toast = {
                        on: true,
                        message: action.message,
                        duration: action.duration
                    }
                    break
                case constants.ALERT:
                    _state.alert = {
                        on: true,
                        title: action.title,
                        message: action.message,
                        ok: action.ok,
                        okLabel: action.okLabel
                    }
                    break
                case constants.CONFIRM:
                    _state.confirm = {
                        on: true,
                        title: action.title,
                        message: action.message,
                        ok: action.ok,
                        okLabel: action.okLabel,
                        cancel: action.cancel,
                        cancelLabel: action.cancelLabel
                    }
                    break
            }
            this.emitChange()
        })
    }

    emitChange() {
        this.emit(constants.CHANGE)
    }

    addChangeListener(callback) {
        this.on(constants.CHANGE, callback)
    }

    removeChangeListener(callback) {
        this.removeListener(constants.CHANGE, callback)
    }

    resetState() {
        for (let c in _state) {
            Object.assign(_state[c], _initialState[c])
        }
    }

    getState() {
        return _state
    }

    getInitialState() {
        return _initialState
    }
}

export default new DialogStore()